package com.gitee.wsl.jvm.reflect.autobox

import com.gitee.wsl.jvm.reflect.ReflectionUtils.cast
import java.sql.Timestamp
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId

class InstantTypeAutoboxer : TypeAutoboxer<Instant> {
    override fun supports(type: Class<*>): Boolean {
        return Instant::class.java == type
    }

    override fun autobox(value: Any, type: Class<Instant>): Instant {
        if (value is Timestamp) {
            return cast(value.toInstant())
        } else if (value is Long) {
            return cast(Timestamp(value).toInstant())
        } else if (value is LocalDateTime) {
            return value.atZone(ZoneId.systemDefault()).toInstant()
        }  else if (value is CharSequence) {
            return Instant.parse(value)
        }
        throw UnsupportedOperationException(
            String.format(
                "Cannot autobox %s of type %s to %s",
                value,
                value.javaClass.name,
                Instant::class.java.name
            )
        )
    }
}
